import axios from 'axios'
import vue from '@/main.js'

axios.defaults.timeout = 30000
axios.defaults.baseURL = ''

let count = 0
/* eslint-disable */
let reqInt, resInt
/* eslint-enable */

//http request 拦截器
function addReqInt() {
  reqInt = axios.interceptors.request.use(
    config => {
      count++
      vue.$toast.loading({
        message: 'Loading...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0
      })
      return config
    },
    err => {
      count--
      vue.$toast.clear()
      vue.$toast(err.toString())
      return Promise.reject(err)
    }
  )
}

//http response 拦截器
function addResInt() {
  resInt = axios.interceptors.response.use(
    response => {
      count--
      if (count === 0) {
        vue.$toast.clear()
      }
      if (response.data.code !== 0) {
        vue.$toast(response.data.data.message)
      }
      return response
    },
    error => {
      count--
      if (count === 0) {
        vue.$toast.clear()
      }
      vue.$toast(error.toString())
      return Promise.reject(error)
    }
  )
}

addReqInt()
addResInt()

//移除拦截器
export function removeInt() {
  count = 0
  axios.interceptors.response.eject(resInt)
}
export function addInt() {
  removeInt()
  addResInt()
}

export default axios
